package com.market.service.impl;

import com.market.entity.Role;
import com.market.mapper.RoleMapper;
import com.market.mapper.UserMapper;
import com.market.service.RoleService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public Role findById(Long id) {
        return roleMapper.findById(id);
    }

    @Override
    public List<Role> findByName(String roleName) {
        return roleMapper.findByName(roleName);
    }
    
    @Override
    public PageResult<Role> findByPage(String roleName, String roleCode, Integer currentPage, Integer pageSize) {
        // 计算偏移量
        Integer offset = (currentPage - 1) * pageSize;
        
        // 查询分页数据
        List<Role> roles = roleMapper.findByPage(roleName, roleCode, offset, pageSize);
        
        // 查询总记录数
        int totalCount = roleMapper.countByCondition(roleName, roleCode);
        
        // 返回分页结果
        return new PageResult<>(currentPage, pageSize, (long) totalCount, roles);
    }

    @Override
    public Map<String, Object> add(Role role) {
        Map<String, Object> result = new HashMap<>();
        
        // 设置创建时间
        role.setCreationDate(new java.sql.Timestamp(System.currentTimeMillis()));
        
        // 设置创建者(当前登录用户)
        Long currentUserId = SessionUtil.getCurrentUserId();
        if (currentUserId != null) {
            role.setCreatedBy(currentUserId);
        } else {
            // 如果无法获取当前用户ID，则设置为默认系统用户ID
            role.setCreatedBy(1L); // 设置默认管理员ID
        }
        
        try {
            int rows = roleMapper.add(role);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "添加角色成功");
                result.put("data", role);
            } else {
                result.put("flag", false);
                result.put("message", "添加角色失败");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "添加角色失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> update(Role role) {
        Map<String, Object> result = new HashMap<>();
        
        // 设置修改时间
        role.setModifyDate(new java.sql.Timestamp(System.currentTimeMillis()));
        
        // 设置修改者(当前登录用户)
        Long currentUserId = SessionUtil.getCurrentUserId();
        if (currentUserId != null) {
            role.setModifyBy(currentUserId);
        } else {
            // 如果无法获取当前用户ID，则设置为默认系统用户ID
            role.setModifyBy(1L); // 设置默认管理员ID
        }
        
        try {
            int rows = roleMapper.update(role);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "修改角色成功");
                result.put("data", role);
            } else {
                result.put("flag", false);
                result.put("message", "修改角色失败，可能角色不存在");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "修改角色失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> deleteById(Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否有关联的用户
            if (hasRelatedUsers(id)) {
                result.put("flag", false);
                result.put("message", "该角色下存在用户，不能删除");
                return result;
            }
            
            int rows = roleMapper.deleteById(id);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "删除角色成功");
            } else {
                result.put("flag", false);
                result.put("message", "删除角色失败，可能角色不存在");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "删除角色失败: " + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public boolean hasRelatedUsers(Long roleId) {
        return userMapper.countByRoleId(roleId) > 0;
    }
}
